package scala.day03

import scala.io.Source

object Demo05StudentTest {
  def main(args: Array[String]): Unit = {
    /**
      *
      * 2、统计总分大于年级平均分的学生
      *
      */
    //读取score表
    val scores: List[String] = Source.fromFile("data/score.txt").getLines().toList
    //读出student表
    val students: List[String] = Source.fromFile("data/students.txt").getLines().toList
    //取出学生id和科目成绩
    val idAndScore: List[(String, Double)] = scores.map(f => {
      val split: Array[String] = f.split(",")
      (split(0),split(2).toDouble)
    })
    //取出学生id和学生姓名
    val idAndName: List[(String, String)] = students.map(f => {
      val split: Array[String] = f.split(",")
      (split(0),split(1))
    })
    //根据学生id分组
    val group: Map[String, List[(String, Double)]] = idAndScore.groupBy(f => f._1)
    //计算学生总分
    val idAndSum: Map[String, Double] = group.map(f => {
      val id: String = f._1
      val ss: List[Double] = f._2.map(i => i._2)
      val sum: Double = ss.sum
      (id,sum)
    })
    //求年级平均分
    val Scores: Iterable[Double] = idAndSum.values
    val avgScore: Double = Scores.sum/Scores.size
    val scoreFilter: Map[String, Double] = idAndSum.filter(p => {
      val score: Double = p._2
      score>avgScore
    })
    //将学生id换成姓名
    val nameAndScore: List[(String, String)] = idAndName
    nameAndScore.map(f => {
      val id: String = f._1
      val name: String = idAndName.toMap.getOrElse(id,"无名者")
      val score: Double = scoreFilter.getOrElse(id,0)
      (name,score)
    }).filter(p => p._2!=0).foreach(println)
  }
}
